<template>
  <div>
    <!-- 面包屑 -->
    <!-- <el-breadcrumb
      separator-class="el-icon-arrow-right"
      style="margin-bottom:20px"
    >
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/admin/goods' }"> 商品管理 </el-breadcrumb-item>
    </el-breadcrumb> -->
    <MyBreadCrumb
      title="商品管理"
      path="goods"
    ></MyBreadCrumb>
    <el-button
      type="success"
      @click="add"
    >添加商品</el-button>
    <el-button
      type="danger"
      @click="exportExcel"
    >导出数据</el-button>
    <el-pagination
      background
      layout="total, sizes,prev, pager, next,jumper"
      :total="allData.length"
      @prev-click="changePage"
      @next-click="changePage"
      @current-change="changePage"
      :page-sizes="[10,15,20]"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      v-if="tableData.length!==0"
    >
    </el-pagination>
    <!-- 商品列表 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      stripe
      border
      :id="domId"
    >
      <!-- column 列  表格的td  prop 对应数据的key  label td显示表头信息 -->
      <el-table-column
        prop="id"
        label="#"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        label="商品名称"
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="图片"
        align="center"
      >
        <!-- 自定义模板显示图片  插槽 -->
        <template slot-scope="scope">
          <!-- <img
            :src="scope.row.pic"
            style="width:150px;height:150px"
            alt=""
          > -->
          <el-image
            style="width:200px;"
            :src="scope.row.pic"
            :preview-src-list="[scope.row.pic]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="price"
        label="价格"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="buyCount"
        label="已购买数"
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
      >
        <!-- slot-scopde作用域插槽  子组件传参到父组件 -->
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <!-- 危险性操作 不可逆操作  提示是否确认操作
              此处使用的气泡确认框
           -->
          <el-popconfirm
            title="确认删除商品吗？"
            @confirm="handleDelete(scope.$index, scope.row)"
          >
            <el-button
              size="mini"
              type="danger"
              slot="reference"
            >删除</el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>
    <!-- 抽屉组件  添加和编辑商品 -->
    <el-drawer
      :title="formStatus?'添加商品':'编辑商品'"
      :visible.sync="dialog"
      direction="ltr"
      custom-class="demo-drawer"
      ref="drawer"
    >
      <div class="demo-drawer__content">
        <!-- 添加商品表单 -->
        <el-form :model="form">
          <el-form-item
            label="名称"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <!-- 
            actions 上传地址
            name 代表服务端接收文件的字段
            on-success 上传成功后调用方法  上传后获取到上传地址
            before-upload 上传前调用方法  限制上传的大小和类型
           -->
          <el-upload
            class="avatar-uploader"
            :action="url.upload"
            name="filename"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <!-- 预览图片 data存储存储imageUrl变量 -->
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
            >
            <!-- 上传点击的+ -->
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>
          </el-upload>
          <el-form-item
            label="图片"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.pic"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="价格"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.price"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="已购买数"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.buyCount"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="dialog = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submit"
          >{{formStatus?'添加':'保存'}}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import url from '@/config/url'
export default {
  data() {
    return {
      // 商品列表
      tableData: [],
      // 抽屉显示状态
      dialog: false,
      // 抽屉的标题
      // title: '添加商品',
      // 表单状态是添加true还是修改false保存
      formStatus: true,
      // 表单的数据项
      form: {
        name: '',
        pic: '',
        price: '',
        buyCount: ''
      },
      formLabelWidth: '80px',
      // 全部数据
      allData: [],
      // 当前页码
      page: 1,
      // 每页显示数量
      pageSize: 10,
      // 总页数
      pageCount: 0,
      // 上传地址
      url: url,
      // 上传后图片地址
      imageUrl: '',
      // 导出excel绑定DOM id
      domId: 'exportGoods',
      // 导出excel文件的名称
      filename: '商品数据导出'
    }
  },
  created() {
    this.loadAllData()
    this.loadData()
  },
  methods: {
    // 导出excel表格
    exportExcel() {
      this.$exportExcel(this.domId, this.filename)
    },
    handleSizeChange(value) {
      this.page = 1
      this.pageCount = 0
      this.pageSize = value
      this.loadData()
    },
    // 点击页码数翻页
    // currentChange(value) {
    //   console.log('当前页:', value)
    // },
    // 点击上一页下一页翻页
    changePage(value) {
      console.log(value)
      // 修改翻页的页码数
      this.page = value
      // 加载翻页数据
      this.loadData()
    },
    // 加载商品列表数据
    loadData() {
      this.$http
        .get(url.goods + '?_page=' + this.page + '&_limit=' + this.pageSize)
        .then((res) => {
          this.tableData = res.data
          // 从响应header头获取总页数
          let link = res.headers.link
          let tmp = link.split(',')
          let index = tmp.length - 1
          this.pageCount = parseInt(
            tmp[index]
              .split(';')[0]
              .replace('<http://127.0.0.1:3000/goods?_page=', '')
              .replace('&_limit=1>', '')
          )
          // 翻页
          // this.page++
        })
    },
    loadAllData() {
      this.$http.get(url.goods).then((res) => {
        this.allData = res.data
      })
    },
    // 添加表单
    add() {
      this.dialog = true
      this.form = {}
      this.formStatus = true
      this.imageUrl = ''
    },
    // 添加|修改商品提交
    submit() {
      let message = ''
      if (this.form.name === undefined) {
        message = '商品名称不能为空'
      }
      if (this.form.price === undefined) {
        message = '价格不能为空'
      }
      if (this.form.pic === undefined) {
        message = '图片地址不能为空'
      }
      if (this.form.buyCount === undefined) {
        message = '购买数量不能为空'
      }
      if (message !== '') {
        this.$message({
          message: message,
          duration: 700,
          type: 'warning'
        })
        return
      }
      // if (
      //   this.form.name === undefined ||
      //   this.form.price === undefined ||
      //   this.form.buyCount === undefined ||
      //   this.form.pic === undefined
      // ) {
      //   this.$message({
      //     message: '数据不能为空',
      //     duration: 700,
      //     type: 'warning'
      //   })
      //   return
      // }
      if (this.formStatus) {
        // 添加操作
        // axios.post(接口地址,数据项[对象结构])
        this.$http.post(url.goods, this.form).then((res) => {
          // 发送请求完毕 返回响应
          // 关闭抽屉
          this.dialog = false
          if (res.data.id) {
            this.$message({
              type: 'success',
              message: '商品添加成功',
              duration: 700
            })
            // 确认添加成功后，可以把数据追加到商品显示列表中
            // this.tableData.push({ ...this.form, id: res.data.id })
            window.location.reload()
          } else {
            this.$message({
              type: 'error',
              message: '商品添加失败',
              duration: 700
            })
          }
        })
      } else {
        // 修改提交
        // PUT http://127.0.0.1:3000/goods/${id}  通过id修改数据
        this.$http
          .put(url.goods + '/' + this.form.id, this.form)
          .then((res) => {
            // 发送请求完毕 返回响应
            // 关闭抽屉
            this.dialog = false
            if (res) {
              this.$message({
                type: 'success',
                message: '商品修改成功',
                duration: 700
              })
            } else {
              this.$message({
                type: 'error',
                message: '商品添加失败',
                duration: 700
              })
            }
          })
      }
    },
    // 删除商品
    handleDelete(index, row) {
      console.log(row)
      // http://127.0.0.1:3000/goods/1  参数形式
      this.$http.delete(url.goods + '/' + row.id).then((res) => {
        if (res.data) {
          this.$message({
            type: 'success',
            message: '商品删除成功',
            duration: 700
          })
          // 删除成功后 刷新页面 或者删除商品列表的显示数据
          this.tableData.splice(index, 1)
        } else {
          this.$message({
            type: 'error',
            message: '商品删除失败',
            duration: 700
          })
        }
      })
    },
    // 编辑商品
    handleEdit(index, row) {
      // 打开抽屉
      this.dialog = true
      // 抽屉的表单数据显示 当前要编辑的信息
      this.form = row
      // 修改表单的状态 修改为编辑
      this.formStatus = false
      // 将原有的图片数据 赋值给imageURL显示
      this.imageUrl = this.form.pic
    },
    // 上传前校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传成功后处理
    handleAvatarSuccess(res, file) {
      // res 服务端上传接口返回的信息
      console.log(res)
      // 添加预览图
      // this.imageUrl = URL.createObjectURL(file.raw)
      if (res.code === 0) {
        // 将上传的文件地址设置显示
        this.imageUrl = 'http://127.0.0.1:5000/static/img/' + res.data.filename
        // 替换表单中图片的地址
        this.form.pic = this.imageUrl
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/* 样式属性穿透 */
/* ::v-deep(.el-input__inner) {
  width: 80%;
} */
.demo-drawer__content {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>